package com.cynteka.cyfoman.ui;

import org.apache.commons.io.FileUtils;
import org.jdesktop.swingx.treetable.FileSystemModel;

import javax.swing.tree.TreePath;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: ukman
 * Date: 19.07.2011
 * Time: 11:33:18
 */
public class ExtendedFileSystemModel extends FileSystemModel {

    private static final String DIRNAME_RE = "([0-9]*)_([^_]*)_([^\\-]*)\\-([^_]*)_(.*)";
    private static final Pattern DIRNAME_PATTERN = Pattern.compile(DIRNAME_RE);

    public enum COLUMNS {
        NAME("Имя"),
        SIZE("Размер"),
        NUMBER("Номер"),
        DATE("Дата"),
        COMPANY("Компания"),
        EMPLOYEE("Сотрудник"),
        SUBJECT("Тема"),;

        private final String label;

        COLUMNS(String label) {
            this.label = label;
        }

    }

    public ExtendedFileSystemModel(File root) {
        super(root);
    }

    public ExtendedFileSystemModel() {
    }

    public void refresh() {
        File root = getRoot();//, f1 = root.listFiles()[0];
        for (File f : root.listFiles()) {
            this.modelSupport.fireTreeStructureChanged(new TreePath(new Object[]{root, f}));
        }
//      this.modelSupport.fireTreeStructureChanged(new TreePath(new Object[]{getRoot()}));
        // this.modelSupport.fireNewRoot();
//        this.valueForPathChanged(new TreePath(new Object[]{getRoot()}), getRoot());
    }

    @Override
    public int getColumnCount() {
        return COLUMNS.values().length;
    }

    @Override
    public Class<?> getColumnClass(int column) {
        return String.class;
    }

    @Override
    public String getColumnName(int column) {
        return COLUMNS.values()[column].label;
    }

    @Override
    public Object getValueAt(Object node, int column) {
        COLUMNS col = COLUMNS.values()[column];
        File f = (File) node;
        int group = -1;
        switch (col) {
            case NAME:
                return f.getName();
            case SIZE:
                return FileUtils.sizeOf(f);
            case NUMBER:
                group = 1;
                break;
            case DATE:
                group = 2;
                break;
            case COMPANY:
                group = 3;
                break;
            case EMPLOYEE:
                group = 4;
                break;
            case SUBJECT:
                group = 5;
                break;

            default:
                // throw new IllegalArgumentException("Wrong column index : " + column);
        }
        if (group > 0 && f.isDirectory()) {
            String dirName = f.getName();
            Matcher matcher = DIRNAME_PATTERN.matcher(dirName);
            if (matcher.matches()) {
                return matcher.group(group);
            }
        }
        return "";
    }
}
